package fr.n7.sma.view;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Scrollable;
import javax.swing.SwingUtilities;

import fr.n7.sma.model.listeners.AgentNewResourcesListener;

public class ResourceCharts extends JPanel implements AgentNewResourcesListener, Scrollable{

	private static final long serialVersionUID = -5964840342658801897L;

	private Map<String, ResourceChart> chartFrames;
	private Container in;

	
	public Dimension getPreferredScrollableViewportSize() {
		return getPreferredSize();
	}

	
	public int getScrollableUnitIncrement(Rectangle visibleRect,
			int orientation, int direction) {
		return 20;
	}

	
	public int getScrollableBlockIncrement(Rectangle visibleRect,
			int orientation, int direction) {
		return 60;
	}

	
	public boolean getScrollableTracksViewportHeight() {
		return false;
	}

	
	public boolean getScrollableTracksViewportWidth() {
		return true;
	}

	public ResourceCharts(){
		super();
		in = this;
		in.setLayout(new BoxLayout(in, BoxLayout.Y_AXIS));
		chartFrames = new HashMap<String, ResourceChart>();
		JButton refresh = new JButton("Raffraichir");
		refresh.addActionListener(new ActionListener(){

			
			public void actionPerformed(ActionEvent e) {
				majGUI();
			}
			
		});
		add(refresh);
	}

	public void setColor(String name, Color color){
		chartFrames.get(name).setColor(color);
	}
	
	public ResourceCharts(String[] resourcesNames){
		this();
		chartFrames = new HashMap<String, ResourceChart>();
		for(String name : resourcesNames){
			addChart(name);
		}
	}

	private void addChart(String name){
		ResourceChart rc = new ResourceChart(name);
		chartFrames.put(name, rc);
		in.add(rc);
		validate();
		revalidate();
		repaint();
	}

	
	public void newResourceDiscovered(String name, int deplNumberFromLast) {
		if(!chartFrames.containsKey(name)){
			addChart(name);
		}
		chartFrames.get(name).addNewValue(deplNumberFromLast);
	}

	public void majGUI(){
		for(String name : chartFrames.keySet()){
			SwingUtilities.invokeLater(chartFrames.get(name));
		}
	}

}
